﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudChartLib
{
    /// <summary>
    /// 云图
    /// </summary>
    public class CloudChart
    {
        private readonly int ChartWidth, ChartHeight;
        private readonly RGB[] Colors;

        /// <summary>
        /// 初始化云图
        /// </summary>
        /// <param name="chartWidth">图宽度</param>
        /// <param name="chartHeight">图高度</param>
        /// <param name="colors">颜色列表，代表值由低到高</param>
        public CloudChart(int chartWidth, int chartHeight, RGB[] colors)
        {
            ChartWidth = chartWidth;
            ChartHeight = chartHeight;

            Colors = colors;
        }

        /// <summary>
        /// 创建云图
        /// </summary>
        /// <param name="data">数据源</param>
        /// <param name="method">插值方法</param>
        /// <param name="setPixel">设置像素回调函数，(row,col,color)</param>
        public void CreateChart(double[,] data, InterpolateMethod method, Action<int, int, RGB> setPixel)
        {
            int rowNum = data.GetLength(0);
            int colNum = data.GetLength(1);

            double[,] mapData = Interpolation.Interpolate(data, ChartHeight, ChartWidth, method);

            double min = double.MaxValue;
            double max = double.MinValue;
            for (int i = 0; i < rowNum; i++)
            {
                for (int j = 0; j < colNum; j++)
                {
                    min = Math.Min(data[i, j], min);
                    max = Math.Max(data[i, j], max);
                }
            }

            int colorLevel = Colors.Length;
            double gap = (max - min) / (colorLevel - 1);
            for (int i = 0; i < ChartHeight; i++)
            {
                for (int j = 0; j < ChartWidth; j++)
                {
                    int level = (int)((mapData[i, j] - min) / gap);
                    setPixel(i, j, Colors[level]);
                }
            }
        }

        /// <summary>
        /// 创建云图
        /// </summary>
        /// <param name="data">数据源</param>
        /// <param name="method">插值方法</param>
        /// <param name="setPixel">设置像素回调函数，(row,col,color)</param>
        public void CreateChart(double[,] data,double minValue,double maxValue, InterpolateMethod method, Action<int, int, RGB> setPixel)
        {
            int rowNum = data.GetLength(0);
            int colNum = data.GetLength(1);

            double[,] mapData = Interpolation.Interpolate(data, ChartHeight, ChartWidth, method);

           

            int colorLevel = Colors.Length;
            double gap = (maxValue - minValue) / (colorLevel - 1);
            for (int i = 0; i < ChartHeight; i++)
            {
                for (int j = 0; j < ChartWidth; j++)
                {
                    int level = (int)((mapData[i, j] - minValue) / gap);
                    setPixel(i, j, Colors[level]);
                }
            }
        }
    }
}
